<template>
  <div class="dashboard-container">
    <div class="app-container">
      <page-tools :show-before="true">
        <span slot="before">共{{ page.total }}条记录</span>
        <template slot="after">
          <el-button size="small" type="warning" @click="$router.push('/import')">导入</el-button>
          <el-button size="small" type="danger" @click="exportEmployee">导出</el-button>
          <el-button :disabled="!dz('addEmployee')" size="small" type="primary" @click="showDialog = true">新增员工</el-button>
        </template>
      </page-tools>
      <!-- 放置表格和分页 -->
      <el-card>
        <el-table border :data="list">
          <el-table-column label="序号" sortable="" type="index" :index="getIndex" />
          <!-- 添加缩略图 -->
          <el-table-column label="缩略图" width="200px">
            <template #default="scope">
              <img v-imgerr="require('@/assets/common/head.jpg')" class="thumbnail" :src="scope.row.staffPhoto" alt="" @click="showQRCode(scope.row.staffPhoto)">
            </template>
          </el-table-column>
          <el-table-column label="姓名" sortable="" prop="username" />
          <el-table-column label="工号" sortable="" prop="workNumber" />
          <el-table-column width="120" label="聘用形式" sortable="" prop="formOfEmployment" :formatter="formOfEmployment" />
          <el-table-column label="部门" sortable="" prop="departmentName" />
          <el-table-column width="120" label="入职时间" sortable="">
            <template #default="scope">
              {{ scope.row.timeOfEntry | formatDate }}
            </template>
          </el-table-column>
          <el-table-column width="120" label="账户状态" sortable="">
            <template #default="scope">
              <el-switch
                :value="scope.row.enableState === 1"
              />
            </template>
          </el-table-column>
          <el-table-column label="操作" sortable="" fixed="right" width="280" prop="enableState">
            <template #default="scope">
              <el-button type="text" size="small" @click="$router.push('employees/detail/' + scope.row.id)">查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="assignRole(scope.row.id)">角色</el-button>
              <el-button type="text" size="small" @click="deleteEmployee(scope.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination
            layout="prev, pager, next"
            :total="page.total"
            :page-size="page.size"
            @current-change="currentChange"
          />
        </el-row>
      </el-card>

      <!-- 弹窗组件 -->
      <AddDemployee :show-dialog.sync="showDialog" @addEmployee="getEmployeeList" />

      <!-- 添加二维码 -->
      <el-dialog title="二维码" :visible="isShowQRCode" @close="isShowQRCode = false">
        <el-row style="height: 400px" type="flex" justify="center" align="middle">
          <canvas ref="myCanvas" />
        </el-row>
      </el-dialog>

      <!-- 角色弹框 -->
      <AssignRole ref="assignRole" :show-role-dialog.sync="showRoleDialog" :user-id="userId" />
    </div>
  </div>
</template>

<script>
import QRCode from 'qrcode'
import EmployeeEnum from '@/api/constant/employees'
import { getEmployeeList, delEmployee } from '@/api/employees'
import { formatDate } from '@/api/filters'
import AddDemployee from './components/add-employee.vue'
import AssignRole from './components/assign-role.vue'
export default {
  components: {
    AddDemployee,
    AssignRole
  },
  data() {
    return {
      list: [],
      page: {
        page: 1,
        size: 5,
        total: 0
      },
      showDialog: false,
      isShowQRCode: false, // 二维码弹框
      showRoleDialog: false, // 觉得弹框
      userId: ''
    }
  },
  created() {
    // 渲染员工数据
    this.getEmployeeList()
  },
  methods: {
    // 角色函数
    assignRole(id) {
      // 关闭弹窗
      this.showRoleDialog = true
      // 触发子组件事件
      this.$refs.assignRole.getDataByID(id)
      // 暂存id
      this.userId = id
    },
    // 员工二维码
    showQRCode(url) {
      if (url) {
        // 弹出弹窗
        this.isShowQRCode = true
        // 显示二维码
        this.$nextTick(() => {
          QRCode.toCanvas(this.$refs.myCanvas, url, {
            width: 300,
            color: {
              dark: '#407ffe'
            }
          })
        })
      }
    },
    // 渲染员工数据
    async getEmployeeList() {
      const { rows, total } = await getEmployeeList(this.page)
      this.list = rows.map(item => {
        return {
          ...item,
          enableState: item.enableState || 6
        }
      })
      this.page.total = total
    },
    // 分页的显示
    currentChange(newPage) {
      // 修改当前页的设定
      this.page.page = newPage
      // 刷新页面
      this.getEmployeeList()
    },
    // 显示分页页码的叠加
    getIndex(index) {
      return index + 1 + (this.page.page - 1) * (this.page.size)
    },
    // 枚举数据的使用
    formOfEmployment(row, col, cell, index) {
      const obj = EmployeeEnum.hireType.find(item => item.id === cell)
      return obj ? obj.value : '未知形式'
    },
    // 导出数据函数
    async exportEmployee() {
      // // 1. 按需加载库
      const { export_json_to_excel } = await import('@/vendor/Export2Excel')
      // console.log(export_json_to_excel)
      // export_json_to_excel({
      //   header: ['姓名', '手机', '工号'],
      //   data: [
      //     ['大壮', '12366698569', 666],
      //     ['老壮', '12366696524', 222],
      //     ['小壮', '12452225854', 999]
      //   ]
      // })
      // 2. 加载员工数组
      const { rows } = await getEmployeeList({ page: 1, size: this.page.total })
      // console.log(rows)
      // 拿完数据, 咱们就要准备生成文件所需
      // 3.1. header数组
      // 3.2. data数组(里面再套数组是各个员工行数据, 顺序跟 header 一样)
      // 所以我们需要一个 表头中文跟后端 api 响应数据英文字段对照的字典
      const dict = {
        '手机号': 'mobile',
        '姓名': 'username',
        '入职日期': 'timeOfEntry',
        '聘用形式': 'formOfEmployment',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName'
      }
      // 生成表头
      const header = Object.keys(dict)
      // console.log(header)
      const newData = rows.map(userObj => {
        return this.obj2array(userObj, dict)
      })
      console.log(rows)
      console.log(newData)
      // 4. 生成导出结果
      export_json_to_excel({
        header,
        data: newData
      })
    },
    obj2array(userObj, dict) {
      const userArray = []
      // 这里应该按表头顺序
      // 从用户对象提取数据放入数组中
      for (const key in dict) {
        // 遍历到的每个 key 都是表头中文字段
        // 转换成英文 key
        const enKey = dict[key]
        // 从用户对象中提取相应数据
        const value = userObj[enKey]
        // push到数组中
        // 本来直接将数据推入即可, 但是如果是时间相关或者聘用形式
        // 需要额外处理
        if (enKey === 'timeOfEntry' || enKey === 'correctionTime') {
          // 处理时间
          // 之前有一堆函数注册过滤器, 虽然这里用不了过滤器, 但是对应的函数
          // 按照 js 原生的导入方式用起来还是没问题的
          userArray.push(formatDate(value))
        } else if (enKey === 'formOfEmployment') {
          // 处理聘用形式
          const obj = EmployeeEnum.hireType.find(item => item.id === value)
          userArray.push(obj ? obj.value : '未知形式')
        } else {
          userArray.push(value)
        }
      }
      return userArray
    },
    // 删除员工
    async deleteEmployee(id) {
      try {
        // 二次确认
        await this.$confirm('您确定删除该员工吗')
        // 发请求
        await delEmployee(id)
        // 成功提示
        this.$message.success('删除成功')
        // 刷新页面
        if (this.list.length === 1 && this.page.page > 1) {
          this.page.page--
        }
        this.getEmployeeList()
      } catch (error) {
        console.log(error)
      }
    }
  }
}
</script>

<style scoped>
.thumbnail{
  width: 180px;
  height: 180px;
  /* // 设置宽高后保持图片比例不变 */
  object-fit: cover;
  border-radius: 20px;
}
</style>
